<template>
  <div style="height: 100%;width: 100%;">
    <div class="titleLabel" :style="{ width: `${wrapW}` }">
      {{ title }}
      <div style="display: inline-flex;width: 100px; justify-content: space-between;">
        <div style="background-color: blue; width: 36px; height: 36px; text-align: center;" @click="littleClick()">-
        </div>
        <div style="background-color: blue; width: 36px; height: 36px; text-align: center;" @click="bigClick()">+</div>
      </div>
    </div>
    <div class="wrap" :style="{ backgroundImage: `${mainBgImgUrl}`, width: `${wrapW}`, height: `${wrapH}` }" id="wrap">
      <van-uploader v-if="beforUpload" class="unload" :after-read="afterRead"></van-uploader>
      <img v-else class="item" id="img" border="0" :src="imgUrl" />
      <canvas id="cover" :width="currentH" :hidden="!isShow" :height="currentH"></canvas>
    </div>

    <div class="leftView" :style="{ left: `${leftValue}` }">
      <div style="width: 100%;max-height: 60%; min-height: 20%; overflow-y:scroll;overflow-x:hidden;">
        <van-grid :border="false" :column-num="3" style="width: 100%; height: 100%;" v-if="preList.length > 0">
          <van-grid-item v-for="value in preList" :key="value">
            <img :src="value" alt="" style="width: 100%;height: auto;">
          </van-grid-item>
        </van-grid>
      </div>

      <div style="display: block;">
        <button @click="getImg" class="getImgButton">预览效果</button>
        <button @click="batchDownload" class="saveImgButton">下载图片</button>
        <van-uploader v-if="!beforUpload" :after-read="afterRead">
          <button @click="saveImg" class="saveImgButton">重新上传</button>
        </van-uploader>
      </div>
    </div>
  </div>
</template>
<script>
import { Toast, Uploader } from "vant";
import html2canvas from "html2canvas";
import JSZip from 'jszip'
import FileSaver from 'file-saver'

import axios from 'axios'
// import Bg2 from "@/assets/bg2.png";

// 把路径指向文件转成ArrayBuffer对象
const getFile = url => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      responseType: 'arraybuffer'
    }).then(data => {
      resolve(data.data)
    }).catch(error => {
      reject(error.toString())
    })
  })
}
export default {
  data() {
    return {
      productId: '',
      title: '',
      zoomVal: 1,
      left: 0,
      top: 0,
      currentX: 0,
      currentY: 0,
      flag: false,
      Bg2: '',
      isShow: true,
      imgUrl: "",
      beforUpload: true,
      wrapW: "1000px",
      minWrapW: "1000px",
      wrapWValue: 0,
      wrapH: "1000px",
      wrapHValue: 0,
      mainBgImgUrl: '',
      drawX: 0,
      drawY: 0,
      preList: [],
      urlList: [],
      currentH: 500,
      testH: 0,
      leftValue: ''
    };
  },
  created() {
    // 界面构建时开始获取url里携带的参数
    this.bus.$emit('loading', true);
    let h = document.documentElement.clientHeight || document.body.clientHeight;
    this.currentH = h - 130
    if (this.currentH < 650) {
      console.log(this.currentH)
      this.wrapW = 650 + 'px'
      this.leftValue = 750 + 'px'

      this.wrapH = 650 + 'px'
    } else if (this.currentH >= 650 && this.currentH <= 1000) {
      this.wrapW = this.currentH + 'px'
      this.leftValue = (this.currentH + 100) + 'px'
      this.wrapH = this.currentH + 'px'
    } else {
      console.log(this.currentH)
      this.currentH = 1000;
      this.wrapW = 1000 + 'px'
      this.leftValue = 1100 + 'px'

      this.wrapH = 1000 + 'px'
    }

    // this.currentH = 650;
    // this.wrapW = 650 + 'px'
    // this.wrapH = 650 + 'px'
    let productId = this.$route.query.productId;
    this.productId = productId;
    let _this = this;
    this.$apiFun.getProductDetail({ 'productId': productId }).then((res) => {
      console.log(res);
      var data = res.data;
      // console.log(data);

      _this.mainBgImgUrl = data.bgUrl;
      _this.title = data.title;
      _this.Bg2 = data.fgUrl;
      _this.bus.$emit('loading', false);
      var radius = _this.currentH / 2000;
      _this.wrapWValue = data.width * radius;
      _this.wrapHValue = data.height * radius;
      _this.drawX = data.x * radius;
      _this.drawY = data.y * radius;
      setTimeout(() => {
        _this.drawBg(_this.currentH);

      }, 500)
    })
  },
  methods: {
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file);
      this.imgUrl = file.content;
      this.beforUpload = false;
      this.$nextTick(() => {
        window.addEventListener("mousewheel", this.bbimg);
        this.startDrag(
          document.getElementById("img"),
          document.getElementById("img")
        );
      });

    },

    // 下载图片
    downloadImage(url) {
      // 如果是在网页中可以直接创建一个 a 标签直接下载
      let a = document.createElement("a");
      a.href = url;
      a.download = "首页截图";
      a.click();
    },
    //批量下载方法
    batchDownload() {
      if (this.imgUrl == '') {
        Toast.fail('请上传样板图片');
        return;
      }
      const zip = new JSZip()
      let _this = this;
      _this.preList.forEach(function (item, index) {
        let fileName = '图片' + (index + 1);
        zip.file(fileName + '.png', item.substring(22), { base64: true })
        if (index == _this.preList.length - 1) {
          zip.generateAsync({ type: 'blob' }).then(content => {
            FileSaver.saveAs(content, _this.title + '.zip')
          })
        }

      })

    },

    drawBg(h) {
      let imgBg = new Image();
      imgBg.src = this.Bg2;
      var canvas = document.getElementById("cover"); // 获取canvas对象
      var ctx = canvas.getContext("2d"); // 创建二维对象
      console.log(ctx);

      // 背景
      imgBg.onload = function () {
        console.log(imgBg);
        ctx.drawImage(imgBg, 0, 0, h, h);
        ctx.save();
      };
    },
    littleClick() {
      var o = document.getElementById("img");
      this.zoomVal -= 15 / 1200;
      o.style.transform = "scale(" + this.zoomVal + ")";
    },
    bigClick() {
      var o = document.getElementById("img");
      this.zoomVal += 15 / 1200;
      o.style.transform = "scale(" + this.zoomVal + ")";
    },
    upload(file) {
      let formData = new FormData()
      // 向formData实例中追加属性 (参数1：属性名 参数2：属性值)
      formData.append('file', file)
      formData.append('productId', this.productId)

      console.log(formData);//这里输出的是一个空的formData对象，因为formData是加密处理的我们看不到其内容，但的的确确添加进去了。
      this.$apiFun.uploadFile(formData).then((res) => {
        console.log(res)
        //   console.log(res.data.data);
        if (res.code == '0000') {
          this.preList = res.data;
          Toast.clear()
        }
      })

    },
    getImg() {
      if (this.imgUrl == '') {
        Toast.fail('请上传样板图片');
        return;
      }
      Toast.loading({
        duration: 20000, // 持续展示 toast
        forbidClick: true,
        message: "请求中...",
        mask: true
      });
      console.log('位置' + this.drawY)
      setTimeout(() => {
        html2canvas(document.getElementById("wrap"), {
          backgroundColor: null, // 画出来的图片有白色的边框,不要可设置背景为透明色（null）
          useCORS: true, // 支持图片跨域
          x: this.drawX,
          y: this.drawY,
          width: this.wrapWValue,
          height: this.wrapHValue,
          borderRadius: "10px",
        }).then((canvas) => {
          // 截图用img元素承装，显示在页面的上
          let img = new Image();
          img.src = canvas.toDataURL("image/png"); // toDataURL :图片格式转成 base64
          console.log(img.src);
          this.upload(this.base64ToFile(img.src, 'test.png'))
          // document.getElementById('test').appendChild(img)

          // 如果你需要下载截图，可以使用a标签进行下载
          // let a = document.createElement('a')
          // a.href = canvas.toDataURL('image/jpeg')
          // a.download = 'test'
          // a.click()
        });
      }, 500);
      this.isShow = false;
      setTimeout(() => {
        this.isShow = true;

      }, 500)

    },
    // 保存图片
    saveImg() {
      if (this.imgUrl == '') {
        Toast.fail('请上传样板图片');
        return;
      }
      let that = this;
      this.preList.forEach(function (item, index) {
        // let downloadName = 'preview' + index;//文件名
        // let imgData = item;//base64
        // that.downloadFile(downloadName, imgData);
        let a = document.createElement('a')
        this.urlList.push(item);
        a.href = item
        a.download = 'preview' + index
        a.click()
      })
    },
    base64ToFile(urlData, fileName) {
      let arr = urlData.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bytes = atob(arr[1]); // 解码base64
      let n = bytes.length
      let ia = new Uint8Array(n);
      while (n--) {
        ia[n] = bytes.charCodeAt(n);
      }
      return new File([ia], fileName, { type: mime });
    },
    // 图片缩放
    bbimg(event) {
      console.log(event.wheelDelta, event);
      var o = document.getElementById("img");
      this.zoomVal += event.wheelDelta / 1200;
      if (this.zoomVal >= 0.2) {
        o.style.transform = "scale(" + this.zoomVal + ")";
      } else {
        this.zoomVal = 0.2;
        o.style.transform = "scale(" + this.zoomVal + ")";
        return false;
      }
    },
    // 获取相关CSS属性
    getCss(o, key) {
      return o.currentStyle
        ? o.currentStyle[key]
        : document.defaultView.getComputedStyle(o, false)[key];
    },
    // 拖拽的实现
    startDrag(bar, target, callback) {
      if (this.getCss(target, "left") !== "auto") {
        this.left = this.getCss(target, "left");
      }
      if (this.getCss(target, "top") !== "auto") {
        this.top = this.getCss(target, "top");
      }
      let that = this;

      // o是移动对象
      bar.onmousedown = function (event) {
        that.flag = true;
        if (!event) {
          event = window.event;
          // 防止IE文字选中
          bar.onselectstart = function () {
            return false;
          };
        }
        var e = event;
        that.currentX = e.clientX;
        that.currentY = e.clientY;
      };
      document.onmouseup = function () {
        that.flag = false;
        if (that.getCss(target, "left") !== "auto") {
          that.left = that.getCss(target, "left");
        }
        if (that.getCss(target, "top") !== "auto") {
          that.top = that.getCss(target, "top");
        }
      };
      document.onmousemove = function (event) {
        let e = event || window.event;

        if (that.flag) {
          let nowX = e.clientX,
            nowY = e.clientY;
          let disX = nowX - that.currentX,
            disY = nowY - that.currentY;
          target.style.left = parseInt(that.left) + disX + "px";
          target.style.top = parseInt(that.top) + disY + "px";
          console.log(target.style);
          if (typeof callback === "function") {
            callback(
              (parseInt(that.left) || 0) + disX,
              (parseInt(that.top) || 0) + disY
            );
          }

          if (event.preventDefault) {
            event.preventDefault();
          }
          return false;
        }
      };
    },
  },

};
</script>
<style scoped>
.wrap {
  /* width: 400px;
  height: 400px; */
  /* margin-left: 100px; */
  /* margin-top: 100px; */
  /* bottom: 100px; */
  overflow: hidden;
  position: relative;
  /* background-color: antiquewhite; */
  /* background-image: url("../assets/bg1.jpg"); */
  /* background-image: url(https://img95.699pic.com/element/40032/1090.png_860.png); */
  /* background-repeat: no-repeat; */
  /* background-size: contain; */
}

.titleLabel {
  font-size: 30px;
  position: absolute;
  top: 0;
  display: inline-flex;
  justify-content: space-between;
  width: 100%;
}

.leftView {
  background-color: white;
  position: absolute;
  right: 0;
  top: 0;
  min-width: 400px;
  height: 100%;
  text-align: center;
  /* display: block; */
}

#imageTofile {
  position: absolute;
  overflow: hidden;
  pointer-events: none;
}

.getImgButton {
  /* border: none; */
  border: 1px solid #cccccc;
  width: 80%;
  min-width: 320px;
  max-width: 400px;
  height: 64px;
  border-radius: 8px;
  background-color: white;
  font-size: 22px;
  margin: 10px;
}

.saveImgButton {
  border: none;
  width: 80%;
  min-width: 320px;
  max-width: 400px;
  height: 64px;
  border-radius: 8px;
  font-size: 22px;
  margin: 10px;

}

.unload {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 100;
  transform: translate(-50%, -50%);
}

.item {
  position: absolute;
  height: 100%;
  width: auto;
  cursor: move;
}

#cover {
  position: absolute;
  pointer-events: none;
}
</style>
